<template>
  <div class="loginbox">
    <!-- 遮罩层 -->
    <div class="mask" @click="useLogin.LoginModalShow(false)"></div>
    <!-- 登录的盒子 -->
    <div class="login">
      <!-- 关闭按钮 -->
      <div class="close" @click="useLogin.LoginModalShow(false)"></div>
      <!-- 导航切换 -->
      <section>
        <a
          :class="{ active: from.isShowLogin }"
          href="javascript:;"
          @click="from.isShowLogin = true"
          >手机号码登录</a
        >
        |
        <a
          :class="{ active: !from.isShowLogin }"
          href="javascript:;"
          @click="showWeiXin"
          >微信号码登录</a
        >
      </section>
      <div class="content">
        <!-- 手机号输入框 -->
        <div class="phonelogin" v-show="from.isShowLogin">
          <div class="row">
            <input
              v-model="from.phone"
              type="text"
              placeholder="请输入手机号"
            />
          </div>
          <!-- 滑块验证 -->
          <div class="row_s">
            <slideVerify ref="block"></slideVerify>
          </div>
          <!-- 短信输入框 -->
          <div class="row">
            <input
              type="text"
              v-model="from.dx_txtVal"
              placeholder="请输入短信验证码"
            />
            <button
              v-show="!from.isShowCount"
              class="btn btncode"
              @click="getCode"
            >
              获取验证码
            </button>
            <button v-show="from.isShowCount" class="btn btncod">
              剩余{{ from.count }}秒
            </button>
          </div>
          <div class="row">
            <!-- 登录按钮 -->
            <button class="btn btnlogin" @click="subLogin">登录</button>
          </div>
        </div>
        <!-- 微信二维码容器 -->
        <div class="qrlogin" v-show="!from.isShowLogin" id="weiXin"></div>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { inject, onMounted, onUpdated, reactive, ref } from "vue";
import { useRoute, useRouter } from "vue-router";
import { useShowLoginStore } from "@/store/showLogin"; //登录框-pinia
import { useToastStore } from "@/store/showToast"; //提示-pinia
import { useSliderStore } from "@/store/slider"; //滑块-pinia
import { userInfoStore } from "@/store/userInfo"; //用户信息=-pinina
import slideVerify from "@/common/slideVerify.vue"; //滑块验证组件
import { SlideVerifyInstance } from "vue3-slide-verify";
import { validatePhoneNumber } from "@/utils"; //手机号效验
import { bindingAPI, PhoneLogin, SendPhoneAPI, UserAPI } from "@/http/api";
const emit = defineEmits(["fn"]);
const useLogin = useShowLoginStore(); //登录框-pinia
const useToast = useToastStore(); //提示框-pinia
const useSlider = useSliderStore(); //滑块-pinia
const useInfo = userInfoStore(); //用户信息-pinia
const route = useRoute();
const router = useRouter();

const from = reactive({
  isShowLogin: true, //控制登录方式切换
  phone: "", //手机号
  dx_txtVal: "", //短信验证码
  isShowCount: false, //控制count显示还是隐藏
  count: 10, //获取验证码倒计时数字
});

//微信登录
const showWeiXin = () => {
  from.isShowLogin = false;
  //获取二维码并展示,申请微信登录二维码
  window.WxLogin({
    id: "weiXin",
    appid: "wx67cfaf9e3ad31a0d", // 这个appid要填死
    scope: "snsapi_login",
    redirect_uri: "https://sc.wolfcode.cn/cms/wechatUsers/PCLogin", // 扫码成功后重定向的接口
    // state填写编码后的url
    state: encodeURIComponent(
      window.btoa("http://127.0.0.1:8080" + route.path)
    ),
    // 调用样式文件
    href: "data:text/css;base64,LmltcG93ZXJCb3ggLnRpdGxlLA0KLmltcG93ZXJCb3ggLmluZm8gew0KICAgIGRpc3BsYXk6IG5vbmU7DQp9DQo=",
  });
};

//封装效验手机号和滑块验证码方法
const toVerify = () => {
  //1.判断手机号 如果效验不通过 需要提示 需要return
  if (!validatePhoneNumber(from.phone)) {
    // 调用弹出提示方法
    useToast.ToastShowModel({
      isShow: true,
      msg: "请输入正确的手机号码",
      type: "error",
    });
    return;
  }
  // //2.判断滑块验证码 如果效验不通过 需要提示 需要return
  if (useSlider.msg != "拼图成功") {
    //提示
    useToast.ToastShowModel({
      isShow: true,
      msg: "请进行滑块验证",
      type: "error",
    });
    return;
  }

  return true; // 上面两个判断如果都不成立就return一个true;
};

//点击获取验证码
const getCode = () => {
  // 1.验证手机号和滑块拼图
  if (!toVerify()) return; //验证不通过，后面代码不执行
  //2.验证通过，发起验证码请求
  console.log(from.phone);
  SendPhoneAPI({ phone: from.phone }).then((res) => {
    if (!res) return; //如果res为undefined
    if (res.code == 0) {
      //页面需要倒计时效果(循环定时器 递减数字count)
      from.isShowCount = true;
      let timer = setInterval(() => {
        from.count--;
        if (from.count == 0) {
          //停止定时器，还原count的值
          clearInterval(timer);
          from.count = 10;
          from.isShowCount = false;
        }
      }, 1000);
    }
  });
};

//点击登录
const subLogin = () => {
  // 1.验证手机号和验证滑块验证码
  if (!toVerify()) return;
  //2. 验证短信验证码(非空判断)
  if (!from.dx_txtVal.trim()) {
    useToast.ToastShowModel({
      isShow: true,
      msg: "请输入验证码",
      type: "error",
    });
    return;
  }
  //3.发登录请求
  let uuid = localStorage.getItem("uuid");
  let token = ref();
  console.log("uuid:", uuid);
  if (uuid) {
    //有uuid就是微信已经绑定了手机号，直接就可以登录请求了
    console.log("准备发起关联请求");
    bindingAPI({
      verifyCode: from.dx_txtVal,
      phone: from.phone,
      uuid: uuid,
    }).then((res) => {
      token.value = res["x-auth-token"];
      console.log(token.value);
    });
  } else {
    //没有uuid就是微信没有绑定手机号，需要注册登录
    console.log("普通手机号登录请求");
    PhoneLogin({
      verifyCode: from.dx_txtVal,
      phone: from.phone,
    }).then((res) => {
      //3.3 存储token(登录凭证,后续请求用户信息等需要用到)
      localStorage.setItem("token", res["x-auth-token"]);
    });
  }
  //3.1 提示
  useToast.ToastShowModel({
    isShow: true,
    msg: "登录成功",
    type: "success",
  });
  //3.2 隐藏登录框
  useLogin.LoginModalShow(false);
  //3.4 切换按钮(显示购物车按钮)
  useLogin.changeLoginEd(true);
  //3.5 清除本地的uuid
  if (uuid) {
    localStorage.removeItem("uuid");
  }
  //登录成功后请求用户信息,调用pinia中的changeUserInfo方法
  useInfo.UserInfoList();
  //重载topBar
  emit("fn", 2);
};
// useInfo.UserInfoList(); //一开始调用默认的用户信息
</script>

<style lang="less" scoped>
.loginbox {
  width: 100%;
  height: 100%;
  position: fixed;
  left: 0;
  top: 0;
  .mask {
    width: 100%;
    height: 100%;
    background-color: rgba(0, 0, 0, 0.5);
  }
  .login {
    padding-top: 28px;
    box-sizing: border-box;
    position: absolute;
    inset: 0;
    margin: auto;
    width: 555px;
    height: 423px;
    background-image: url("@/assets/img/login-box-bg.png");
    .close {
      background-image: url("@/assets/img/close.png");
      width: 22px;
      height: 22px;
      position: absolute;
      top: 6px;
      right: 56px;
    }
    section {
      text-align: center;
      line-height: 50px;
      a {
        text-decoration: none;
        color: #000;
        &.active {
          color: orange;
        }
      }
    }
    .content {
      text-align: center;
      width: 350px;
      margin: 0 auto;
      // background: pink;
      .phonelogin {
        margin-top: 10px;
        .row {
          display: flex;
          margin-bottom: 20px;
          input {
            flex: 1;
            height: 45px;
            text-indent: 1em;
            outline: none;
          }
          .btn {
            width: 80px;
            margin-left: 10px;
            background: rgb(10, 50, 142);
            color: #fff;
            border: none;
          }
          .btncode {
            margin-left: 10px;
          }
          .btnlogin {
            width: 100%;
            height: 45px;
          }
        }
      }
    }
  }
}

// 滑块验证样式
.row_s {
  margin-bottom: 20px;
  :deep(.slide-box) {
    width: 100%;
    position: relative;
    box-sizing: border-box;
    canvas {
      position: absolute;
      left: 0;
      top: -120px;
      display: none;
      width: 100%;
      box-sizing: border-box;
    }
    .slide-verify-block {
      width: 85px;
      height: 136px;
    }
    .slide-verify-refresh-icon {
      top: -120px;
      display: none;
    }
    &:hover {
      canvas {
        display: block;
      }
      .slide-verify-refresh-icon {
        display: block;
      }
    }
  }
}
</style>
